package tk.cful.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author kolesnikov
 */
public class DigestHelper {

    private int roundsNumber = 256;
    private static DigestHelper instance = null;

    private DigestHelper() {
    }

    public static DigestHelper getInstance() {
        if (instance == null)
            instance = new DigestHelper();
        return instance;
    }

    public String sha256Hash(String password, String salt) {
        String digest = null;
        String saltDigest;
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            for (int i = 0; i < roundsNumber; i++) {
                md.reset();
                md.update((salt + i).getBytes());
                saltDigest = encode(md.digest());
                md.reset();
                md.update((password + i + saltDigest).getBytes());
                digest = encode(md.digest());
            }
            return digest;
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
    }

    public String encode(byte[] digest) {
        StringBuffer hexString = new StringBuffer();
        for (int i = 0; i < digest.length; i++) {
            String hex = Integer.toHexString(0xff & digest[i]);
            if (hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public void setRoundsNumber(int roundsNumber) {
        this.roundsNumber = roundsNumber;
    }

    public int getRoundsNumber() {
        return roundsNumber;
    }
}
